import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'dva';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { Divider, Button, Tooltip, message, Popconfirm, Spin } from 'antd';
import {
  apiCustomerGetList,
  apiCustomerAdd,
  apiCustomerUpdate,
  apiCustomerDelete,
} from '@/services/otherServices';
import { PlusOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons';
import Search from './Search';
import { history } from 'umi';
import Detail from './Detail';
import { useRequest, useUpdateEffect } from '@umijs/hooks';
import {
  btnPermission,
  diffSubmitData,
  formatDateTimeStamp,
  mergeLoading,
} from '@/utils/utils';
import moment from 'moment';

let detailForm: any = null;

const List = (props: any) => {
  const { btnPermissionLoading } = props;
  const actionRef = useRef<ActionType>();
  const [visible, setVisible] = useState(false);
  const [searchValue, setSearchValue] = useState({});
  const [size, setSize]: any = useState('large');
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize]: any = useState(10);
  const [dataSource, setDataSource] = useState([]);

  const [editId, setEditId] = useState(undefined);
  const [editItem, setEditItem] = useState(undefined);

  /*
   * 列表请求
   * */
  const { loading: pageLoading, run: getPage } = useRequest(
    apiCustomerGetList,
    {
      manual: true,
      onSuccess: (res, params) => {
        setDataSource(res.data);
        setTotal(res.total);
      },
    },
  );

  /*
   * 新建请求
   * */
  const { loading: addLoading, run: add } = useRequest(apiCustomerAdd, {
    manual: true,
    debounceInterval: 500,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.success('添加成功');
      setVisible(false);
      getPageData();
    },
  });

  /*
   * 编辑请求
   * */
  const { loading: updateLoading, run: update } = useRequest(
    apiCustomerUpdate,
    {
      manual: true,
      debounceInterval: 500,
      loadingDelay: 200,
      onSuccess: (res, params) => {
        message.success('更新成功');
        setVisible(false);
        getPageData();
      },
    },
  );

  /*
   * 删除请求
   * */
  const { loading: delLoading, run: del } = useRequest(apiCustomerDelete, {
    manual: true,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.success('删除成功');
      if (total % 10 === 1) {
        setCurrent(current - 1);
      } else {
        getPageData();
      }
    },
  });

  const getPageData = () => {
    getPage({
      pageNo: current,
      pageSize: pageSize,
      ...searchValue,
    });
  };

  useUpdateEffect(() => {
    getPageData();
  }, [current, pageSize, searchValue]);

  useEffect(() => {
    getPageData();
  }, []);

  const columns: ProColumns<any>[] = [
    {
      title: '编号',
      dataIndex: 'a',
      width: 80,
      hideInSearch: true,
      render: (text, record, index) => (
        <span>{(current - 1) * 10 + index + 1}</span>
      ),
    },
    {
      title: '客户',
      dataIndex: 'customerCompany',
    },
    {
      title: '联系人',
      dataIndex: 'contact',
      hideInSearch: true,
    },

    {
      title: '联系方式',
      dataIndex: 'contactPhoneNo',
      hideInSearch: true,
    },
    {
      title: '收货人',
      dataIndex: 'consignee',
      hideInSearch: true,
    },
    {
      title: '收货人联系方式',
      dataIndex: 'consigneePhoneNo',
      hideInSearch: true,
    },
    {
      title: '收货地址',
      dataIndex: 'deliveryAddress',
      hideInSearch: true,
    },
  ];
  if (
    btnPermission(history.location.pathname, [
      'btn_customer_del',
      'btn_customer_edit',
    ])
  ) {
    columns.push({
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          {btnPermission(history.location.pathname, 'btn_customer_edit') && (
            <span>
              <a
                onClick={() => {
                  if (record.dutyDate) {
                    record.dutyDate = moment(record.dutyDate);
                  }
                  detailForm.setFieldsValue({
                    ...record,
                  });
                  setVisible(true);
                  setEditId(record.id);
                  setEditItem(record);
                }}
              >
                <Tooltip mouseEnterDelay={0.5} title="编辑">
                  <FormOutlined style={{ fontSize: 18 }} />
                </Tooltip>
              </a>
            </span>
          )}
          {btnPermission(history.location.pathname, 'btn_customer_del') && (
            <span>
              <Divider type="vertical" />
              <Popconfirm
                title="确认删除？"
                placement="topRight"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  del(record.id);
                }}
              >
                <a>
                  <Tooltip mouseEnterDelay={0.5} title="删除">
                    <DeleteOutlined style={{ fontSize: 18 }} />
                  </Tooltip>
                </a>
              </Popconfirm>
            </span>
          )}
        </>
      ),
    });
  }

  return (
    <div className={'spin-bg-white'}>
      <Spin tip={'权限获取中,请稍等...'} spinning={btnPermissionLoading}>
        <Detail
          afterClose={() => {
            setEditId(undefined);
            setEditItem(undefined);
            detailForm.resetFields();
          }}
          visible={visible}
          onCancel={() => setVisible(false)}
          getForm={(from: any) => (detailForm = from)}
          loading={mergeLoading(addLoading, updateLoading)}
          editId={editId}
          onOk={async () => {
            await detailForm.validateFields();
            const value = detailForm.getFieldsValue();
            if (value.dutyDate) {
              value.dutyDate = formatDateTimeStamp(value.dutyDate);
            }
            if (editId) {
              const data = diffSubmitData(editItem, value);

              update({
                id: editId,
                ...data,
              });
            } else {
              add(value);
            }
          }}
        />

        <ProTable<any>
          loading={pageLoading}
          dataSource={dataSource}
          actionRef={actionRef}
          tableAlertRender={false}
          search={false}
          scroll={{ x: 'max-content' }}
          options={{
            fullScreen: false,
            density: true,
            reload: false,
            setting: true,
          }}
          rowKey="id"
          size={size}
          onSizeChange={(s: any) => {
            setSize(s);
          }}
          headerTitle={
            btnPermission(history.location.pathname, 'btn_customer_search') && (
              <Search
                loading={pageLoading}
                callbackValue={(value: any) => {
                  setCurrent(1);
                  setSearchValue(value);
                }}
              />
            )
          }
          toolBarRender={(action, { selectedRows }) => [
            btnPermission(history.location.pathname, 'btn_customer_add') && (
              <Button
                onClick={() => setVisible(true)}
                icon={<PlusOutlined />}
                type="primary"
              >
                新建
              </Button>
            ),
          ]}
          pagination={{
            pageSize: pageSize,
            total: total,
            current: current,
            onChange: (page, pageSize) => {
              setCurrent(page);
              setPageSize(pageSize);
            },
            onShowSizeChange: (current, size) => {
              setCurrent(current);
              setPageSize(size);
            },
          }}
          columns={columns}
        />
      </Spin>
    </div>
  );
};

export default connect(({ globalModel }: any) => ({
  btnPermissionLoading: globalModel.btnPermissionLoading,
}))(List);
